package com.magina.impl.system;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.magina.api.entity.system.TSysMenu;
import com.magina.api.entity.system.TSysRole;
import com.magina.api.entity.system.TSysRoleMenu;
import com.magina.api.service.service.system.MenuService;
import com.magina.api.service.service.system.RoleService;

import com.magina.mapper.system.TSysRoleMapper;
import com.magina.mapper.system.TSysRoleMenuMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;


@Service(interfaceClass = RoleService.class)
public class RoleServiceImpl implements RoleService {

    @Autowired
    private TSysRoleMapper roleMapper;

    @Autowired
    private TSysRoleMenuMapper roleMenuMapper;

    @Autowired
    private MenuService menuService;

    @Override
    public PageInfo<TSysRole> queryRoleList(TSysRole role) {

        PageHelper.startPage(role.getPageNum(), role.getPageSize());

        return PageInfo.of(roleMapper.selectAllRoleList(role));
    }

    @Override
    public TSysRole getRole(int roleId) {
        if(roleId == 0){
           return new TSysRole();
        }
        return roleMapper.selectByPrimaryKey(roleId);
    }

    @Override
    public void addRole(TSysRole role) {
        //保存角色role
        roleMapper.insert(role);

        batchAddRoleMenu(role);
    }

    @Override
    public void editRole(TSysRole role) {

        roleMapper.updateByPrimaryKeySelective(role);

        //删除该角色绑定的菜单
        roleMenuMapper.delRoleAndMenuByRoleId(role.getId());

        batchAddRoleMenu(role);

    }

    @Override
    public void delRole(int roleId) {

        roleMapper.deleteByPrimaryKey(roleId);

        roleMenuMapper.delRoleAndMenuByRoleId(roleId);
    }

    @Override
    public List<TSysMenu> getMenuListByRoleId(int roleId) {
        return roleMapper.selectMenuByRoleId(roleId);
    }

    @Override
    public List<TSysMenu> getMenuTreeListByRoleId(int roleId){
        List<TSysMenu> menuList = getMenuListByRoleId(roleId);

        return menuService.convertTreeJsonList(menuList);
    }


    /**
     * 批量添加 菜单与角色的绑定表
     * @param role
     */
    private void batchAddRoleMenu(TSysRole role){
        String [] menuArray = role.getMenuIds().split(",");
        List<TSysRoleMenu> roleMenuList = new ArrayList<>();
        TSysRoleMenu roleMenu = null;
        for(String menuId : menuArray){
            roleMenu = new TSysRoleMenu();
            roleMenu.setMenuId(Integer.parseInt(menuId));
            roleMenu.setRoleId(role.getId());

            roleMenuList.add(roleMenu);
        }
        roleMenuMapper.batchInsert(roleMenuList);
    }




}
